var $ = require("../../utils/Ajax.js");
let disp = require("../../utils/broadcast");
var WebIM = require("../../utils/WebIM")["default"];
function SelectUserInfor(that,Infor,Msg){
  if (Msg != ''){
    for (var bx = 0; bx < Infor.length; bx++){
      if (Msg.from == Infor[bx].username){
        Infor[bx].NewMsg = Msg.data
      }
    }
  }
  if (Infor.length >= 1){
    var InforIndex = 0;
    var MemberListArr = wx.getStorageSync('MemberListArr') || [];
    var MsgUserList = wx.getStorageSync('MsgUserList');
    for (var i = 0; i < MsgUserList.length; i++) {
      if (!(MemberListArr.indexOf(MsgUserList[i].username) === false)) {
          MsgUserList.splice(i, 1);
       }
    }
    for (var i = 0; i < Infor.length; i++) {
      var InforI = Infor[i];              
      if (Infor[i].nickName == undefined) {
        $.Ajax("api/getu", "GET", {
          id: Infor[i].username
        }, function (res) {
          if (res.s) {
            InforI.avatarUrl = res.d.user.avatarUrl;
            InforI.nickName = res.d.user.nickName;
            ++InforIndex;
            if (InforIndex == Infor.length) {
              MsgUserList.reverse();
              for (var j = 0; j < MsgUserList.length; j++) {
                Infor.unshift(MsgUserList[j]);        
              }
              console.log(Infor)
              that.setData({
                arr: Infor
              })
            }
          }
        })
      }
    }
  }else{
    var MsgUserList = wx.getStorageSync('MsgUserList');
    for (var i = 0; i < MsgUserList.length;i++){
      if (Msg.from == MsgUserList[i].username) {
        MsgUserList[i].NewMsg = Msg.data
      }
    }
    console.log(MsgUserList)
    that.setData({
      arr: MsgUserList
    })
  }
}

let isfirstTime = true
Page({
  data: {
    // 消息数据
    MsgData: [1,2],
    search_btn: true,
    search_chats: false,
    show_mask: false,
    yourname: "",
    unReadSpotNum: 0,
    unReadNoticeNum: 0,
    messageNum: 0,
    unReadTotalNotNum: 0,
    arr: [],
    show_clear: false
  },

  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "消息"
    }) 

    let me = this;

    //监听未读消息数
    disp.on("em.xmpp.unreadspot", function (message) {
      console.log(message)
      me.setData({
        arr: me.getChatList(),
        unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
      });
      SelectUserInfor(me, me.data.arr, message);
    });

    var Token = wx.getStorageSync('Token');
    var UserInfor = wx.getStorageSync('UserInfor');

    if (Token == '' || Token == null) {

    } else {
      //登录
      getApp().conn.open({
        apiUrl: WebIM.config.apiURL,
        user: UserInfor.openId,
        pwd: "123456",
        grant_type: "password",
        appKey: WebIM.config.appkey
      });
    }
    this.setData({
      arr: this.getChatList(),
      unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
      messageNum: getApp().globalData.saveFriendList.length,
      unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
      unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
    });

    if (getApp().globalData.isIPX) {
      this.setData({
        isIPX: true
      })
    }
  },
  getRoster() {
    console.log("roster_start:")
    let me = this;
    let rosters = {
      success(roster) {
        console.log("roster:")
        console.log(roster)
        var member = [];
        for (let i = 0; i < roster.length; i++) {
          if (roster[i].subscription == "both") {
            member.push(roster[i]);
          }
        }
        wx.setStorage({
          key: "member",
          data: member
        });
        me.setData({ member: member });
        me.listGroups()
      },
      error(err) {
        console.log("err");
        console.log(err);
      }
    };
    WebIM.conn.getRoster(rosters);
  },

  listGroups() {
    var me = this;
    return WebIM.conn.listRooms({
      success: function (rooms) {
        wx.setStorage({
          key: "listGroup",
          data: rooms
        });
        me.getChatList()
      },
      error: function (err) {
        console.log(err)
      }
    });
  },


  getChatList() {
    var that = this;
    var array = [];
    var member = wx.getStorageSync("member");
    var myName = wx.getStorageSync("myUsername");
    var listGroups = wx.getStorageSync('listGroup') || [];
    for (let i = 0; i < member.length; i++) {
      let newChatMsgs = wx.getStorageSync(member[i].name + myName) || [];
      let historyChatMsgs = wx.getStorageSync("rendered_" + member[i].name + myName) || [];
      let curChatMsgs = historyChatMsgs.concat(newChatMsgs);
      if (curChatMsgs.length) {
        let lastChatMsg = curChatMsgs[curChatMsgs.length - 1];
        lastChatMsg.unReadCount = newChatMsgs.length;
        if (lastChatMsg.unReadCount > 99) {
          lastChatMsg.unReadCount = "99+";
        }
        let dateArr = lastChatMsg.time.split(' ')[0].split('-')
        let timeArr = lastChatMsg.time.split(' ')[1].split(':')
        lastChatMsg.dateTimeNum = `${dateArr[1]}${dateArr[2]}${timeArr[0]}${timeArr[1]}${timeArr[2]}`
        lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}时${timeArr[1]}分`
        array.push(lastChatMsg);
      }
    }

    for (let i = 0; i < listGroups.length; i++) {
      let newChatMsgs = wx.getStorageSync(listGroups[i].roomId + myName) || [];
      let historyChatMsgs = wx.getStorageSync("rendered_" + listGroups[i].roomId + myName) || [];
      let curChatMsgs = historyChatMsgs.concat(newChatMsgs);
      if (curChatMsgs.length) {
        let lastChatMsg = curChatMsgs[curChatMsgs.length - 1];
        lastChatMsg.unReadCount = newChatMsgs.length;
        if (lastChatMsg.unReadCount > 99) {
          lastChatMsg.unReadCount = "99+";
        }
        let dateArr = lastChatMsg.time.split(' ')[0].split('-')
        let timeArr = lastChatMsg.time.split(' ')[1].split(':')

        lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}时${timeArr[1]}分`
        lastChatMsg.dateTimeNum = `${dateArr[1]}${dateArr[2]}${timeArr[0]}${timeArr[1]}${timeArr[2]}`
        lastChatMsg.groupName = listGroups[i].name
        array.push(lastChatMsg);
      }
    }

    array.sort((a, b) => {
      return b.dateTimeNum - a.dateTimeNum
    })
    SelectUserInfor(that, that.data.arr,'');
    return array;
  },

  onShow: function () {
    var Token = wx.getStorageSync('Token');
    var UserInfor = wx.getStorageSync('UserInfor');
    if (Token == '' || Token == null) {
      wx.removeStorageSync('Token');
      wx.removeStorageSync('UserInfor');
      wx.switchTab({
        url: '../My/My',
      })
    }

    var that = this;
    setTimeout(function(){
      that.getRoster();
    },2000);
  },


  //	单聊
  into_singleChatRoom: function (detail) {
    //	单聊
    var that = this;
    var my = wx.getStorageSync("myUsername");
    var MyInfor = wx.getStorageSync('UserInfor');
    var openid = detail.currentTarget.dataset.openid;
    var mingzi = detail.currentTarget.dataset.mingzi;
    var avatarUrl = detail.currentTarget.dataset.avatarurl;
    var nameList = {
      your: openid.toLowerCase(),
      yourTou: avatarUrl,
      myName: MyInfor.openId.toLowerCase(),
      myName_: MyInfor.nickName,
      myTou: MyInfor.avatarUrl,
      yourName: mingzi,
    };
    wx.navigateTo({
      url: "../SendMsg/SendMsg?username=" + JSON.stringify(nameList)
    });
  },


  // 点击存茶
  StoreTea: function(){
    wx.navigateTo({
      url: '../StoreTea/StoreTea',
    })
  },

  // 点击系统消息
  SystemMsg: function(){
    wx.navigateTo({
      url: '../SystemMsg/SystemMsg',
    })
  },

  // 点击互动通知
  Interaction: function(){
    wx.navigateTo({
      url: '../Interaction/Interaction',
    })
  },

  // 点击某一个人
  SendMsg: function(e){
    var index = e.currentTarget.dataset.item;
    console.log(index);
    wx.navigateTo({
      url: '../Data/Data?Id=' + index,
    })
  }
})